<template>
  <div v-loading="detailLoading" :class="{ 'mobile-create': showMobilePage }" class="app-container create-user">
    <el-row class="user-form">
      <el-form ref="editUserForm" :model="editUserForm" :rules="editUserRules" :label-position="formAlign" label-width="80px" class="edit-user">
        <div :style="{padding: showMobilePage ? '16px 12px 24px' : '16px 24px 56px'}" class="form-box">
          <Title :title="title" :style="{marginBottom:isDisabled?'7px':'16px'}"/>
          <div :class="[isDisabled ? '' : 'column',showMobilePage && isDisabled?'mobile-info-box':'']" class="info-box">
            <div :class="{'line label':isDisabled}" class="left-box">
              <el-form-item :class="isDisabled && 'disabled-row-item'" :style="{marginBottom:isDisabled?'0':'24px'}" :label="`姓名${isDisabled?'：':''}`" prop="userName">
                <span v-if="isDisabled" class="textValue">{{ editUserForm.userName }}</span>
                <el-input v-if="!isDisabled" v-model="editUserForm.userName" maxlength="50" placeholder="请输入员工真实的中文姓名" name="userName" auto-complete="new-password" type="text" @blur="changeValue" />
              </el-form-item>
              <el-form-item :class="isDisabled && 'disabled-row-item'" :style="{marginBottom:isDisabled?'0':'24px'}" :label="`工号${isDisabled?'：':''}`" prop="jobNumber">
                <span v-if="isDisabled" class="textValue">{{ editUserForm.jobNumber || '--' }}</span>
                <el-input
                  v-if="!isDisabled"
                  v-model="editUserForm.jobNumber"
                  placeholder="请严格按飞书的数据输入员工的工号"
                  name="jobNumber"
                  type="text"
                  @blur="changeValue" />
              </el-form-item>
              <el-form-item :class="isDisabled && 'disabled-row-item'" :label="`用户名${isDisabled?'：':''}`" prop="jobName" style="margin-bottom:0">
                <span v-if="isDisabled" class="textValue">{{ editUserForm.jobName }}</span>
                <el-input v-if="!isDisabled" :disabled="userDisabled" v-model="editUserForm.jobName" name="jobName" type="text" />
              </el-form-item>
              <el-form-item v-if="isDisabled" label="同步时间：" prop="updateTime" class="disabled-row-item" style="margin-bottom:0">
                <span v-if="editUserForm.updateTime" class="textValue">{{ editUserForm.updateTime | standardFormat('YYYY/MM/DD HH:mm') }}</span>
                <span v-else class="textValue">--</span>
              </el-form-item>
            </div>
            <div v-if="isDisabled" class="right-box label">
              <el-form-item label="职位：" prop="post" class="disabled-row-item" style="margin-bottom:0">
                <span class="textValue">{{ editUserForm.post || '--' }}</span>
              </el-form-item>
              <el-form-item label="入职时间：" prop="entryTime" class="disabled-row-item" style="margin-bottom:0">
                <span v-if="editUserForm.entryTime" class="textValue">{{ editUserForm.entryTime | standardFormat('YYYY/MM/DD') }}</span>
                <span v-else class="textValue">--</span>
              </el-form-item>
              <el-form-item label="离职时间：" prop="dimissionTime" class="disabled-row-item" style="margin-bottom:0">
                <span v-if="editUserForm.dimissionTime" class="textValue">{{ editUserForm.dimissionTime | standardFormat('YYYY/MM/DD') }}</span>
                <span v-else class="textValue">--</span>
              </el-form-item>
            </div>
          </div>
          <el-form-item v-if="isShow" label="原密码" prop="oldPwd">
            <el-input v-model="editUserForm.oldPwd" type="password" name="oldPwd" />
          </el-form-item>
          <el-form-item :label="pwdLabel" prop="password">
            <el-input v-model="editUserForm.password" type="password" name="password" />
          </el-form-item>
          <el-form-item label="确认密码" prop="rePassword">
            <el-input v-model="editUserForm.rePassword" type="password" name="rePassword" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email" name="email" type="text" />
          </el-form-item>
          <el-form-item label="微信号" prop="wxCode">
            <el-input v-model="editUserForm.wxCode" type="text" maxlength="50" @input="onWxCodeChange"/>
          </el-form-item>
          <el-form-item label="同步设置" prop="isSync">
            <el-checkbox v-model="editUserForm.isSync" :disabled="!isEditDept" :true-label="1" :false-label="0">自动同步飞书部门</el-checkbox>
          </el-form-item>
          <el-form-item v-if="!isBrand" label-width="0px" class="dept-form">
            <dept-form
              v-for="(item, index) in deptComponents"
              ref="deptForm"
              :key="index"
              :is-edit-admin="isEditDept"
              :dept-list="deptList"
              :dept-rules="item.deptRules"
              :dept-obj="item.deptObj"
              :index="index"
              @isChange="isChange"
              @getParticipate="getParticipate">
              <el-button v-if="index !== 0" slot="del" type="text" size="small" style="margin-left: 17px; width: 12px !important;" @click="delDept(index)">
                <img src="../../../assets/del.png" alt="删除" style="width: 11px; height: 12px">
              </el-button>
            </dept-form>
          </el-form-item>
          <el-button v-if="!isBrand && (hasRouteAuth('crm:userList:deptEdit') || isAdmin)" type="text" class="add-btn" @click.stop="addDept()">添加部门+</el-button>
          <!-- <el-form-item v-if="!isBrand" label="设置：" prop="status">
            <el-checkbox v-model="editUserForm.status" name="status" true-label="1" false-label="0" checked>启用</el-checkbox>
          </el-form-item> -->
        </div>
      </el-form>
    </el-row>
    <fixed-pagination>
      <div class="center">
        <el-button :loading="loading" type="primary" class="submit-btn" size="small" @click="toSave('editUserForm')">保存</el-button>
        <el-button class="back-btn cancel-btn-style" size="small" @click="toClear()">取消</el-button>
      </div>
    </fixed-pagination>
    <el-dialog
      :visible.sync="pwdDialogVisible"
      :append-to-body="true"
      width="480px"
      center
      class="pwd-dialog"
      @close="handleClose">
      <template slot="title">
        <div class="pwd-title" style="padding-top:38px;">
          <img style="width:200px;" src="../../../assets/crm_logo.png" alt="共创平台">
        </div>
      </template>
      <send-pwd-dialog ref="sendPwd" :is-disabled="true" @closeDialog="closeDialog"/>
    </el-dialog>
  </div>
</template>
<script>
import { userCreate, userEdit, getDepartment } from '@/api/user';
import { getInfo } from '@/api/login';
// import { deptList } from '@/api/select';
import { infoEdit, getUserInfo } from '@/api/brand';
import DeptForm from '@/components/DeptForm';
import Title from '@/components/Title';
import SendPwdDialog from '@/components/SendPwdDialog';
import subDeptInfo from '@/mixins/getSubDept';
import verify from '@/mixins/verify';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
import { standardFormat } from '@/filters/date';
import mobileCreate from '@/mixins/mobileCreate';
export default {
  name: 'EditUser',
  filters: {
    standardFormat
  },
  components: { DeptForm, Title, SendPwdDialog },
  mixins: [subDeptInfo, verify, mobileCreate],
  data() {
    return {
      pwdDialogVisible: false,
      editUserForm: {
        userName: '',
        acronym: '',
        jobNumber: '',
        jobName: '',
        oldPwd: '',
        password: '',
        rePassword: '',
        email: '',
        wxCode: '',
        departmentAry: [],
        // subDepartment: [],
        status: '',
        userStatus: '',
        isSync: 1,
        post: '',
        entryTime: '',
        dimissionTime: '',
        updateTime: ''
      },
      deptRules: {
        departmentAry: [{ required: true, trigger: 'change', message: '请选择部门' }]
      },
      pwdLabel: '密码',
      userDisabled: true,
      isDisabled: false,
      userId: '',
      title: '新增用户',
      deptList: [],
      loading: false,
      deptName: '',
      isBrand: false,
      allComponents: [],
      detailLoading: false,
      participate: [] // 是否参与同步
      // departmentAry: [] // 传给接口的部门字段
      // subDepartment: [], // 传给接口的子部门字段【v2.8废弃】
      // subDeptList: [] // 子部门下拉框数据【v2.8废弃】
    };
  },
  computed: {
    ...mapState({
      'userDetail': state => state.user.userInfo
    }),
    isAdmin() {
      if (this.userDetail.userName === '管理员') return true;
      return false;
    },
    deptComponents() {
      this.allComponents.map(item => {
        item.deptRules = this.deptRules;
      });
      return this.allComponents;
    },
    isHightAdmin() {
      return this.hasRouteAuth('crm:userList:admin');
    },
    isEditDept() {
      return this.hasRouteAuth('crm:userList:deptEdit') || this.isAdmin;
    }
  },
  beforeRouteEnter(to, from, next) {
    if (to.name === 'userUpdate') {
      to.meta.isBrand = true;
    }
    next();
  },
  created() {
    this.load();
  },
  methods: {
    hasRouteAuth,
    load() {
      this.userId = Number(this.$route.params.userId) || '';
      if (this.userId) {
        this.title = '编辑用户';
        this.isDisabled = true;
        this.pwdLabel = '新密码';
        this.isShow = true;
        const editUserRules = this.editUserRules;
        const keys = ['userName', 'acronym', 'jobNumber', 'password', 'rePassword'];
        for (const key in editUserRules) {
          if (keys.includes(key)) {
            delete editUserRules[key];
          } else {
            if (this.isHightAdmin) {
              if (key === 'oldPwd') {
                delete editUserRules[key];
              }
            }
          }
        }
        if (this.$route.meta.isBrand) { // isBrand为true时隐藏部门和设置,拼音缩写
          this.isBrand = true;
          this.getInfo();
        } else {
          this.isBrand = false;
          this.userInfo();
        }
      } else {
        this.addDept();
      }
      this.deptInfo();
    },
    deptInfo() { // 获取部门的数据
      getDepartment().then(res => {
        this.deptList = this.getTreeData(res.data);
      }).catch(err => {
        console.error(err);
      });
    },
    // 递归设置children为空数组将值改成null
    getTreeData(data) {
      data.forEach(item => {
        if (Array.isArray(item.children)) {
          if (!item.children.length) {
            item.children = null;
          } else {
            this.getTreeData(item.children);
          }
        }
      });
      return data;
    },
    userInfo() { // 获取原用户列表进来的数据
      this.detailLoading = true;
      getInfo(this.userId).then(async(res) => {
        this.detailLoading = false;
        const { userName, jobNumber, acronym, userStatus, isSync, email, wxCode, post, entryTime, dimissionTime, updateTime, departmentAry } = res.data;
        const editUserForm = this.editUserForm;
        editUserForm.userName = userName;
        editUserForm.jobNumber = jobNumber;
        editUserForm.acronym = acronym;
        editUserForm.jobName = jobNumber + userName;
        editUserForm.status = userStatus.toString();
        editUserForm.email = email;
        editUserForm.wxCode = wxCode;
        editUserForm.isSync = isSync;
        editUserForm.post = post;
        editUserForm.entryTime = entryTime;
        editUserForm.dimissionTime = dimissionTime;
        editUserForm.updateTime = updateTime;
        if (departmentAry && departmentAry.length) {
          departmentAry.forEach((item, index) => {
            const deptObj = {
              departmentAry: item.id,
              cancleParticipate: !item.participate
            };
            this.participate[index] = item.participate;
            this.addDept(deptObj);
          });
        } else {
          this.addDept();
        }
        // this.deptComponents.forEach(item => { // 编辑用户时，部门不是必填项，去除必填限制
        //   item.deptRules.departmentAry[0].required = false;
        // });
      }, result => {
        this.detailLoading = false;
        this.$message.error(result.message);
      });
    },
    getInfo() { // 获取内品用户列表进来获取的数据
      getUserInfo(this.userId).then(res => {
        const { email, jobNumber, name, username, wxCode } = res.data;
        const editUserForm = this.editUserForm;
        editUserForm.email = email;
        editUserForm.wxCode = wxCode;
        editUserForm.jobNumber = jobNumber;
        editUserForm.jobName = username;
        editUserForm.userName = name;
      }, result => {
        this.$message.error(result.message);
      });
    },
    changeValue() { // 拼接用户名
      this.editUserForm.jobName = (this.editUserForm.jobNumber + this.editUserForm.userName).replace(/\s+/g, '');
    },
    createDeptForm(deptObj) { // 定义子组件部门和子部门的值
      return {
        'deptObj': deptObj || {
          departmentAry: [],
          cancleParticipate: false
        },
        'deptRules': this.deptRules
      };
    },
    delDept(index) { // 删除部门
      this.deptComponents.splice(index, 1);
      this.participate.splice(index, 1);
    },
    addDept(deptObj) { // 新增部门
      if (!deptObj) {
        this.participate.push(true);// 默认参与
      }
      this.deptComponents.push(this.createDeptForm(deptObj));
    },
    isChange(id, index) { // 获取部门数据
      // const data = await this.subDeptInfo(id);
      // this.deptComponents[index].deptObj.subDeptList = data.data; // 修改父部门或切换父部门的时候修改子部门的下拉框数据
      // this.deptComponents[index].deptObj.subDepartment = ''; // 修改父部门或切换父部门的时候置空子部门
    },
    onWxCodeChange() { // 微信号去除中文
      this.editUserForm.wxCode = this.editUserForm.wxCode.replace(/[\u4e00-\u9fa5]/g, '').trim();
    },
    getParticipate({ val, index }) { // 获取是否同步
      this.participate[index] = !val;
    },
    add() {
      // this.changeDeptString();
      const editUserForm = this.editUserForm;
      const dptArr = [];
      this.participate.forEach((el, index) => {
        dptArr.push({
          id: editUserForm.departmentAry[index],
          participate: el
        });
      });
      const params = {
        acronym: editUserForm.acronym,
        email: editUserForm.email,
        wxCode: editUserForm.wxCode,
        jobName: editUserForm.jobName,
        jobNumber: editUserForm.jobNumber,
        password: editUserForm.password,
        rePassword: editUserForm.rePassword,
        userName: editUserForm.userName,
        userStatus: editUserForm.userStatus,
        isSync: editUserForm.isSync,
        departmentAry: dptArr
        // subDepartment: JSON.stringify(editUserForm.subDepartment)
      };
      userCreate(params).then(res => {
        this.loading = false;
        this.$message.success('添加成功');
        this.$router.push({
          name: 'user'
        });
      }, result => {
        this.loading = false;
        // this.$message.error(result.message);
      });
    },
    edit() { // 原用户列表进入的编辑
      // this.changeDeptString();
      const editUserForm = this.editUserForm;
      const dptArr = [];
      this.participate.forEach((el, index) => {
        dptArr.push({
          id: editUserForm.departmentAry[index],
          participate: el
        });
      });
      const params = {
        email: editUserForm.email,
        wxCode: editUserForm.wxCode,
        oldPwd: editUserForm.oldPwd,
        password: editUserForm.password,
        rePassword: editUserForm.rePassword,
        userStatus: editUserForm.userStatus,
        isSync: editUserForm.isSync,
        departmentAry: dptArr
        // subDepartment: JSON.stringify(editUserForm.subDepartment)
      };
      userEdit(this.userId, params).then(res => {
        this.loading = false;
        // this.$message.success('修改成功');
        // localStorage.setItem('isSuccess', true);
        // // this.editUserForm.deptName = this.departmentAry;
        // // this.editUserForm.subDepartment = this.subDepartment;
        // localStorage.setItem('changeData', JSON.stringify(this.editUserForm));
        this.$router.push({
          name: 'user'
        });
        this.$store.dispatch('GetInfo');
      }, result => {
        this.loading = false;
        // this.departmentAry = [];
        // this.subDepartment = []; // 初始化部门和子部门
        // this.$message.error(result.message);
      });
    },
    toEdit() { // 内品进入修改用户编辑
      const editUserForm = {
        email: this.editUserForm.email,
        oldPwd: this.editUserForm.oldPwd,
        password: this.editUserForm.password,
        rePassword: this.editUserForm.rePassword
      };
      infoEdit(this.userId, editUserForm).then(res => {
        this.loading = false;
        this.$message.success('修改成功');
        this.$store.dispatch('GetInfo');
        localStorage.setItem('isSuccess', true);
        localStorage.setItem('changeData', JSON.stringify(this.editUserForm));
        this.$router.push({
          name: 'userList'
        });
      }, result => {
        this.loading = false;
        // this.$message.error(result.message);
      });
    },
    toSave(formValue) {
      this.editUserForm.departmentAry = [];
      const editUserForm = this.$refs[formValue];
      const deptFormParams = this.$refs.deptForm.map(item => item.$refs.deptObj);
      const params = [];
      deptFormParams.map(item => {
        params.push(item);
      });
      params.push(editUserForm);
      this.editUserForm.userStatus = Number(this.editUserForm.status);
      this.editUserForm.jobNumber = this.editUserForm.jobNumber.replace(/\s+/g, '');
      this.deptComponents.forEach((item) => {
        this.editUserForm.departmentAry.push(item.deptObj.departmentAry[item.deptObj.departmentAry.length - 1]);
      });
      Promise.all(params.map(this.getFormPromise)).then(res => {
        const validateResult = res.every(item => !!item);
        if (validateResult) {
          this.loading = true;
          if (!this.userId) {
            this.add();
          } else {
            if (this.isBrand) {
              this.toEdit();
            } else {
              this.edit();
            }
          }
        } else {
          return false;
        }
      });
    },
    getFormPromise(form) {
      return new Promise(resolve => {
        form.validate(res => {
          resolve(res);
        });
      });
    },
    toClear() {
      localStorage.setItem('isSuccess', false);
      localStorage.setItem('changeData', '');
      this.$router.push({
        name: this.isBrand ? 'userList' : 'user'
      });
    },
    toAuthPage() {
      if (this.isAdmin) {
        this.$router.push({
          name: 'operatorManage'
        });
      } else {
        this.$router.push({
          name: 'editOperator',
          params: { operatorId: this.userDetail.id }
        });
      }
    },
    resetPass() {
      const params = {
        jobNumber: this.userDetail.jobNumber,
        email: this.userDetail.email
      };
      this.pwdDialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.sendPwd) this.$refs.sendPwd.setEmailAndJobNumber(params);
      });
    },
    closeDialog(close) {
      this.pwdDialogVisible = close;
    },
    handleClose() { // 点击右上角的关闭弹窗
      if (this.$refs.sendPwd) this.$refs.sendPwd.clearPwdForm();
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.create-user {
  margin: 16px;
  .info-box {
    display: flex;
    flex-direction: row;
    margin-bottom: 8px;
    &.column {
      flex-direction: column;
    }
    .left-box{
      width: 50%;
      margin-right: 20px;
    }
    .label{
        .el-form-item__label {
        color: #999999;
      }
    }
    .line{
      border-right: 1px solid #ebeefd;
    }
    .disabled-row-item {
      &::v-deep .el-form-item__label {
        color: #999;
        padding-right: 0;
      }
    }
  }
  .form-box {
    min-height: calc(100vh - 56px);
    background-color: #fff;
  }
  .edit-user {
    &::v-deep {
      .el-form-item {
        margin-bottom: 20px;
        .el-form-item__label {
          font-size: 13px !important;
        }
        .el-input, .el-input__inner {
          width: 320px;
          height: 32px !important;
        }
        .el-checkbox {
          margin-left: 3px;
        }
        .el-form-item__content {
          vertical-align: sub;
        }
        .el-select__caret.el-input__icon.el-icon-arrow-up {
          line-height: 32px;
        }
      }
    }
    .textValue {
      display: block;
      min-width: 150px;
      margin-left: 3px;
    }
    .dept-form {
      margin-bottom: 0 !important;
      &::v-deep .el-form-item__label {
        width: 80px !important;
      }
    }
    .add-btn {
      font-size: 14px;
      padding: 0;
      margin-left: 80px;
    }
    .crm-add-btn {
      ::v-deep .el-form-item__content {
        margin-left: 0 !important;
      }
    }
  }
}
.mobile-create {
  margin-bottom: 60px !important;
  &::v-deep {
    .el-input, .el-input__inner, .el-button {
      width: calc(100vw - 150px) !important;
      height: 32px !important;
    }
  }
}
.mobile-info-box {
  flex-wrap: wrap;
  .line {
    border: none !important;
  }
  &::v-deep {
    .el-form-item {
      width: 100% !important;
    }
  }
}
</style>
